﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dao;
using Web.Utils;

namespace Web.Page
{
    public partial class JCCD_Query : BasePage
    {
        public const string OP_KEY = "op";
        protected const string CONFIRMED = "1";
        protected const string CMD_CONFIRM = "Confirm";

        protected string id;

        JCCD_Dao dao = new JCCD_Dao();
        JCCDMXB_Dao daoMXB = new JCCDMXB_Dao();

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            id = Request.QueryString["id"];

            if (!IsPostBack)
            {
                string op = Request.QueryString["op"];
                this.hdOp.Value = op;
                Cache.Insert(OP_KEY, op);
                string title = "{0}仓单列表";
                string mxbTitle = "{0}仓单明细表";
                this.lbTitle.Text = string.Format(title, op.CompareTo("1000") < 0 ? "进" : "出");
                this.lbMXBTitle.Text = string.Format(mxbTitle, op.CompareTo("1000") < 0 ? "进" : "出");
                this.tbRQStart.Attributes.Add("onclick", "show()");
                this.tbRQEnd.Attributes.Add("onclick", "show()");
                initValue();
                BindGridview();

                Guid jid = new Guid();
                if (id != null && Guid.TryParse(id, out jid))
                {                    
                    CommandEventArgs cea = new CommandEventArgs("VIEW_MXB", String.Format("{0};{1}", id, 0));
                    ViewMxb(null, cea);
                }
            }
        }

        private void initValue()
        {
            // 部门
            Departments_Dao daoDep = new Departments_Dao();
            List<Department> lsDep = daoDep.QueryAll();
            this.ddlBM.DataSource = lsDep;
            this.ddlBM.DataTextField = "Name";
            this.ddlBM.DataValueField = "ID";
            this.ddlBM.DataBind();
            this.ddlBM.Items.Insert(0, new ListItem("请选择", "0"));
        }

        protected void GridView1_PageIndexChanged(object sender, EventArgs e)
        {
            BindGridview();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindGridview();
            SavePageIndex(e.NewPageIndex);
        }

        private void BindGridview()
        {
            GridView1.PageIndex = RestorePageIndex();

            string bh = this.tbBH.Text.Trim();
            string bm = this.ddlBM.SelectedValue.ToString();
            string ry = this.ddlRY.SelectedValue.ToString();
            string cgy = this.ddlCGY.SelectedValue.ToString();

            string lx = hdOp.Value;

            string datetimeStart = this.tbRQStart.Text.Trim();
            string datetimeEnd = this.tbRQEnd.Text.Trim();
            if (!datetimeStart.Equals(string.Empty) && !datetimeEnd.Equals(string.Empty))
            {
                int t = DateTime.Parse(datetimeStart).CompareTo(DateTime.Parse(datetimeEnd));
                if (t > 0)
                {
                    lbResult.Text = "结束时间不能小于开始时间";
                    return;
                }
            }

            List<vJCCD> list = dao.QueryBySqlEx(lx, bm, ry, cgy, datetimeStart, datetimeEnd);
            this.GridView1.DataSource = list;
            this.GridView1.DataBind();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                vJCCD item = (vJCCD)e.Row.DataItem;
                Label lblRQ = ((Label)(e.Row.Cells[5].FindControl("lblRQ")));
                lblRQ.Text = item.RQ.ToString("yyyy-MM-dd HH:ss:dd");
                LinkButton btnConfirm = ((LinkButton)(e.Row.Cells[5].FindControl("btnConfirm")));

                Button btnViewMXB = ((Button)(e.Row.Cells[9].FindControl("btnViewMXB")));
                btnViewMXB.CommandArgument = String.Format("{0};{1}", item.ID.ToString(), item.ZT);
                btnConfirm.CommandArgument = item.ID.ToString();

                Label lblZT = ((Label)(e.Row.Cells[8].FindControl("lblZT")));
                if (item.ZT == 0)
                {
                    lblZT.Text = "待确认";
                    lblZT.ForeColor = System.Drawing.Color.Red;
                    btnConfirm.Visible = true;
                }
                else
                {
                    lblZT.ForeColor = System.Drawing.Color.Green;
                    lblZT.Text = "已确认";
                    btnConfirm.Visible = false;
                    btnConfirm.OnClientClick = null;
                }
            }
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
            int result = dao.Delete(id);
            if (result == 1)
            {
                lbResult.Text = "删除成功";
                BindGridview();
            }
        }


        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string id = (string)e.CommandArgument;

            if (e.CommandName.Equals(CMD_CONFIRM))
            {
                Confirm(id);
            }
        }

        protected void Confirm(string id)
        {
            string jccdid = id;
            JCCD_Dao dao = new JCCD_Dao();
            JCCD jccd = dao.Query(jccdid);
            bool res = false;
            if (jccd.LX.CompareTo("1000") < 0)
            {
                res = dao.ConfirmIn(jccdid);
            }
            else
            {
                List<Guid> less = new List<Guid>();
                res = dao.ConfirmOut(jccdid, ref less);
            }

            if (res)
            {
                lbResult.Text = "确认单据成功。";
                BindGridview();
            }
        }

        private string getLX(string key)
        {
            string str = "";
            switch (key.Trim())
            {
                case "0001":
                    str = "物料采购进仓";
                    break;
                case "1001":
                    str = "物料采购出仓";
                    break;
            }
            return str;
        }

        protected void ddlBM_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ddlRY.Items.Clear();
            string depId = ddlBM.SelectedValue;
            if (depId != "0")
            {
                Guid guid = Guid.Parse(depId);
                using (var context = new Dao.ErpEntities())
                {
                    var query = from d in context.UserInDepartmentSet
                                join u in context.UserSet
                                on d.UserId equals u.Id
                                where d.DepartmentId == guid
                                select new
                                {
                                    Id = d.UserId,
                                    Name = u.Name
                                };
                    List<UserNames> list = new List<UserNames>();
                    if (query.Count() > 0)
                    {
                        foreach (var q in query)
                        {
                            UserNames un = new UserNames();
                            un.Id = q.Id.ToString();
                            un.Name = q.Name;
                            list.Add(un);
                        }
                    }

                    this.ddlRY.DataSource = list;
                    this.ddlRY.DataTextField = "Name";
                    this.ddlRY.DataValueField = "Id";
                    this.ddlRY.DataBind();

                    this.ddlCGY.DataSource = list;
                    this.ddlCGY.DataTextField = "Name";
                    this.ddlCGY.DataValueField = "Id";
                    this.ddlCGY.DataBind();
                }
            }

            this.ddlRY.Items.Insert(0, new ListItem("请选择", "0"));
            this.ddlCGY.Items.Insert(0, new ListItem("请选择", "0"));
        }


        protected class UserNames
        {
            public string Id { get; set; }
            public string Name { get; set; }
        }

        protected void btnAdd_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("~/Page/JCCD_Add.aspx?op=" + this.hdOp.Value);
        }

        protected void btnQuery_Click(object sender, ImageClickEventArgs e)
        {
            BindGridview();
        }

        protected void btnMXB_Click(object sender, EventArgs e)
        {
            
        }

        protected void ViewMxb(object sender, CommandEventArgs e)
        {
            string[] args = e.CommandArgument.ToString().Split(';');
            this.hfSelectedID.Value = args[0];
            this.hfConfirmed.Value = args[1];
            if (CONFIRMED.Equals(this.hfConfirmed.Value))
            {
                this.btnAddMXB.Visible = false;
            }
            else
            {
                this.btnAddMXB.Visible = true;
            }

            BindMXB(args[0]);
        }

        private void BindMXB(string id)
        {
            // 产品 
            ZL_CP_Dao daoCp = new ZL_CP_Dao();
            List<ZL_CP> listcp = daoCp.QueryAll();

            // 物料
            ZL_WL_Dao daoWl = new ZL_WL_Dao();
            List<ZL_WL> listwl = daoWl.QueryAll();

            List<vJCCDMXB> list = daoMXB.QueryByJCCDIDEx(id);
            List<JCCDMXB_Ex> listEx = new List<JCCDMXB_Ex>();

            foreach (vJCCDMXB c in list)
            {
                JCCDMXB_Ex ce = new JCCDMXB_Ex();
                ce.CKBH = c.CKBH;
                ce.CKID = c.CKID;
                ce.CKMC = c.CKMC;
                ce.CWBH = c.CWBH;
                ce.DJ = c.DJ;
                ce.DJLX = c.DJLX;
                ce.DWBH = c.DWBH;
                ce.DWMC = c.DWMC;
                ce.ID = c.ID;
                ce.JCCDID = c.JCCDID;
                ce.SL = c.SL;
                ce.WPID = c.WPID;
                ce.WPLX = GetWPLX(c.WPLX);

                ce.JCSJ = c.JCSJ.ToString("yyyy-MM-dd HH:ss:dd");

                if (c.WPLX == "01")
                {
                    ZL_WL wl = listwl.Find(delegate(ZL_WL p) { return p.ID == c.WPID; });
                    ce.WPBH = wl.BH;
                    ce.WPMC = wl.MC;
                }
                else if (c.WPLX == "02")
                {
                    ZL_CP cp = listcp.Find(delegate(ZL_CP p) { return p.ID == c.WPID; });
                    ce.WPBH = cp.BH;
                    ce.WPMC = cp.BH;
                }

                listEx.Add(ce);
            }

            this.gvMXB.DataSource = listEx;
            this.gvMXB.DataBind();
        }

        protected class JCCDMXB_Ex
        {
            public Guid ID { get; set; }
            public Guid CKID { get; set; }
            public string CKBH { get; set; }
            public string CKMC { get; set; }
            public Guid CWID { get; set; }
            public string CWBH { get; set; }

            public double DJ { get; set; }
            public string DJLX { get; set; }

            public string DWBH { get; set; }
            public string DWMC { get; set; }

            public string JCSJ { get; set; }
            public Guid JCCDID { get; set; }
            public double SL { get; set; }
            public Guid WPID { get; set; }
            public string WPLX { get; set; }
            public string WPBH { get; set; }
            public string WPMC { get; set; }
        }

        private string GetWPLX(string key)
        {
            string name = "";
            switch (key.Trim())
            {
                case "01":
                    name = "物料";
                    break;
                case "02":
                    name = "产品";
                    break;
                case "03":
                    name = "部件";
                    break;
            }

            return name;
        }

        private string GetDJLX(string key)
        {
            string name = "";
            switch (key.Trim())
            {
                case "0001":
                    name = "物料采购进仓";
                    break;
                case "0002":
                    name = "物料调拨进仓";
                    break;
            }
            return name;
        }

        protected void gvMXB_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string id = gvMXB.DataKeys[e.RowIndex].Value.ToString();
            int result = daoMXB.Delete(id);
            if (result == 1)
            {
                lbResult.Text = "删除成功";
                BindMXB(hfSelectedID.Value);
            }
        }

        protected void gvMXB_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton btnDelete = ((LinkButton)(e.Row.Cells[8].FindControl("btnDelete")));

                if (CONFIRMED.Equals(this.hfConfirmed.Value))
                {
                    btnDelete.OnClientClick = null;
                    btnDelete.Enabled = false;
                    // e.Row.Cells[8].Visible = false;
                }
                
            }
        }

        protected void btnAddMXB_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("~/Page/JCCDMXB_Add.aspx?jccdid=" + this.hfSelectedID.Value + "&op=" + hdOp.Value);
        }

    }
}